package org.example.jd.utils;

import org.example.jd.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname HtmlParseUtil
 * @Description
 * @Date 2020/5/20 15:48
 * @Created by 苟晓健
 */
public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
        new HtmlParseUtil().parseJD("java").forEach(System.out::println);
    }


    public List<Content> parseJD(String keywords) throws IOException {

        //获取请求  https://search.jd.com/Search?keyword=java
        String url = "https://search.jd.com/Search?keyword=" + keywords;


        ArrayList<Content> contents = new ArrayList<>();


        //解析网页 (jsoup返回Document 就是浏览器的Document对象)
        Document document = Jsoup.parse(new URL(url), 30000);
        //所有在js中可以使用的方法,在这里都可以使用
        //得到jd商城 商品显示的div
        Element element = document.getElementById("J_goodsList");
        //System.out.println(element);
        //获取所有的<li/>标签
        Elements elements = element.getElementsByTag("li");
        //获取元素里面的内容
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("src");
            //String img = el.getElementsByTag("img").eq(0).attr("source-data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();


            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);

            contents.add(content);
        }
        return contents;
    }

}
